﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;
using TomNet.Utility.Extensions;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Core.Contracts.Identity;

namespace TomNet.IMSC.Web.Areas.Organization.Controllers
{
	[Description("管理-管理员")]
	[GlobalAuthorization]
	public class StaffController : BaseController
    {
		public IStaffContract StaffContract { get; set; }
		public IStaffLoginContract StaffLoginContract { get; set; }
		public TomNet.IMSC.Core.Contracts.Identity.IRoleContract RoleContract { get; set; }
		public IDepartmentContract DepartmentContract { get; set; }
		public IAgentContract AgentContract { get; set; } 
        public IStaffRolesContract StaffRolesContract { get; set; }
        public ISideModuleContract SideModuleContract { get; set; } 
        public IAuthorityContract AuthorityContract { get; set; }
        public IAuthorityGroupContract AuthorityGroupContract { get; set; }
        public IStaffAuthorityContract StaffAuthorityContract { get; set; }


        #region ActionResult Index()

        [Description("管理-管理员列表")]
		public ActionResult Index()
        {
            return View();
        }

		#endregion
		
		#region ActionResult IndexAsync(int pageIndex, int pageSize, string keyWord = "")

		[Description("管理-管理员列表")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult IndexAsync(int pageIndex, int pageSize, string keyWord = "")
		{
			var query = (from a in StaffContract.Entities
						 join b1 in DepartmentContract.Entities on a.DepartmentID equals b1.Id into tempb
						 from b in tempb.DefaultIfEmpty()
						 join c1 in AgentContract.Entities on a.AgentID equals c1.Id into tempc
						 from c in tempc.DefaultIfEmpty() 
						 where (keyWord == "" || a.Name.Contains(keyWord)) && !a.IsDeleted
						 select new
						 {
							 Id = a.Id,
							 Name = a.Name,
							 Sex = a.Sex == 1 ? "男" : "女",
							 Phone = a.Phone,
							 DepartmentID = a.DepartmentID,
                             DepartmentName = b.Name,
                             RoleName = from sr in StaffRolesContract.Entities
                                        join r in RoleContract.Entities
                                        on sr.RoleID equals r.Id
                                        where sr.StaffID == a.Id
                                        select r.Name,
                             AgentID = a.AgentID,
                             AgentName = c.Name,
                             Remark = a.Remark,
                             CreatedTime = a.CreatedTime,
                             Start = SideModuleContract.Entities.Where(m => m.Id == a.SideModuleID).Select(m => m.StartTime).FirstOrDefault(),
                             End = SideModuleContract.Entities.Where(m => m.Id == a.SideModuleID).Select(m => m.EndTime).FirstOrDefault() 
                         });
            var t = query.ToList();

            //数据总数
            var total = query.Count();

			//默认给一个排序的字段
			query = query.OrderBy(m => m.Id);

			//分页(假如total == 0，则取消分页查询，提高性能)
			query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

			//此处可以采用匿名对象 GridData<object>
			GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

			//此处采用重写后的jsonResult
			return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
		}

		#endregion

		#region ActionResult Insert()

		[Description("管理-管理员添加")]
		public ActionResult Insert()
		{
			#region SelectList

			List<SelectListItem> items;

			//角色
			items = new List<SelectListItem>();
			List<Model.DbModels.Identity.Role> infosRole = RoleContract.Entities.ToList();
			foreach (Model.DbModels.Identity.Role info in infosRole)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewBag.selectRole = new SelectList(items, "Value", "Text");

			//部门
			items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Text = "无", Value = "" });

			List<Department> infosDepartment = DepartmentContract.Entities.Where(p => !p.IsDeleted).ToList();
			foreach (Department info in infosDepartment)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewBag.selectDepartment = new SelectList(items, "Value", "Text");

			//代理
			items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Text = "无", Value = "" });

			List<Agent> infosAgent = AgentContract.Entities.Where(p => !p.IsDeleted).ToList();
			foreach (Agent info in infosAgent)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewBag.selectAgent = new SelectList(items, "Value", "Text");

            #endregion
            interan();

            return View();
		}

		#endregion

		#region ActionResult InsertAsync(Staff entity)

		[Description("管理-管理员添加")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult InsertAsync(Staff entity)
		{
			//所有AJAX的结果，返回统一数据格式
			var result = new AjaxResult();
			try
			{
				var query = StaffContract.CheckExists(m => m.Name.Equals(entity.Name));
                var queryl = StaffLoginContract.CheckExists(m => m.LoginType.Equals(1) && m.LoginName.Equals(entity.Phone));
                if (query)
				{
					result.Type = AjaxResultType.Error;
					result.Content = "已经存在相同的信息";
				}
                else if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的手机号";
                }

                {
                    var count = StaffContract.Insert(entity);
                    StaffLoginContract.Insert(new StaffLogin { CreatedTime = DateTime.Now, CreatorId = "0", IsDeleted = false, IsLocked = false, LoginName = entity.Phone, LoginPass = "123456", LoginType = 1, SMSCodeID = 0, StaffID = entity.Id, State = 1, Token = "" });
                    if (count > 0)
					{
						result.Type = AjaxResultType.Success;
						result.Content = "录入成功";
					}
					else
					{
						result.Type = AjaxResultType.Error;
						result.Content = "录入失败";
					}
				}
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

		#endregion

		#region ActionResult Edit(int id)

		[Description("管理-管理员修改")]
		public ActionResult Edit(int id)
		{
			var entity = StaffContract.GetByKey(id);

			//后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
			if (entity == null) throw new Exception("未找到该实体");

			#region SelectList

			List<SelectListItem> items;

			//角色
			items = new List<SelectListItem>();
			List<Model.DbModels.Identity.Role> infosRole = RoleContract.Entities.ToList();
			foreach (Model.DbModels.Identity.Role info in infosRole)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewBag.selectRole = new SelectList(items, "Value", "Text", 0);

			//部门
			items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Text = "无", Value = "" });

			List<Department> infosDepartment = DepartmentContract.Entities.Where(p => !p.IsDeleted).ToList();
			foreach (Department info in infosDepartment)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewBag.selectDepartment = new SelectList(items, "Value", "Text", entity.DepartmentID);

			//代理
			items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Text = "无", Value = "" });

			List<Agent> infosAgent = AgentContract.Entities.Where(p => !p.IsDeleted).ToList();
			foreach (Agent info in infosAgent)
			{
				items.Add(new SelectListItem() { Text = info.Name, Value = info.Id.ToString() });
			}
			ViewBag.selectAgent = new SelectList(items, "Value", "Text", entity.AgentID);

            #endregion

            interan();
            ViewData["entity"] = entity;
            return View();
		}

        #endregion

        #region ActionResult EditAsync(Staff entity)

        [Description("管理-管理员修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditAsync(Staff entity)
        {
            var result = new AjaxResult();
            try
            {
                //var query = StaffContract.CheckExists(m => m.Name.Equals(entity.Name) && m.Id != entity.Id);
                //if (query)
                //{
                //	result.Type = AjaxResultType.Error;
                //	result.Content = "已经存在相同的信息";
                //}
                //else
                //{
                var staffmodel = StaffContract.GetByKey(entity.Id);
                entity.OldID = staffmodel.OldID;
                entity.CreatedTime = staffmodel.CreatedTime;
                entity.CreatorId = staffmodel.CreatorId;
                if (String.IsNullOrEmpty(entity.Remark))
                {
                    entity.Remark = "";
                }
                if (String.IsNullOrEmpty(entity.CreatorId))
                {
                    entity.CreatorId = "0";
                }
                var count = StaffContract.Update(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
                //}
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

		#endregion

		#region ActionResult DeleteAsync(string ids)

		[Description("管理-管理员删除")]
		[HttpPost, AjaxOnly]
		public ActionResult DeleteAsync(string ids)
		{
			var result = new AjaxResult();
			try
			{
				string[] idsStr = ids.Split(new char[] { ',' });
				int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
				StaffContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new Staff { IsDeleted = true });

				result.Type = AjaxResultType.Success;
				result.Content = "删除成功";
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

		#endregion



		#region ActionResult Login(int staffId)

		[Description("管理-登录配置列表")]
		public ActionResult Login(int staffId)
		{
			ViewBag.staffId = staffId;
			return View();
		}

		#endregion

		#region ActionResult LoginAsync(int staffId)

		[Description("管理-登录配置列表")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult LoginAsync(int staffId)
		{
			var query = StaffLoginContract.Entities.Where(p => p.StaffID.Equals(staffId) && !p.IsDeleted);

			//数据总数
			var total = query.Count();

			//默认给一个排序的字段
			query = query.OrderBy(m => m.Id);

			#region Func

			Func<int, string> GetLoginType = delegate (int i)
			   {
				   Model.ViewModels.LoginType enumType = (Model.ViewModels.LoginType)i;
				   return enumType.ToDescription();
			   };

			Func<int, string> GetStateName = delegate (int i) {
				switch (i)
				{
					case 0: return "不可用";
					case 1: return "正常";
					default: return "";
				}
			};

			#endregion

			var infos = query.ToList().Select(p => new
			{
				Id = p.Id,
				LoginType = GetLoginType(p.LoginType),
				LoginName = p.LoginName,
				State = GetStateName(p.State)
			});

			//此处可以采用匿名对象 GridData<object>
			GridData<object> gridData = new GridData<object>() { Total = total, Rows = infos };

			//此处采用重写后的jsonResult
			return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
		}

		#endregion

		#region ActionResult LoginInsert(int staffId)

		[Description("管理-登录配置添加")]
		public ActionResult LoginInsert(int staffId)
		{
			var infoStaff = StaffContract.GetByKey(staffId);

			//后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
			if (infoStaff == null) throw new Exception("未找到相关实体");

			#region SelectList

			List<SelectListItem> items = new List<SelectListItem>();

			//登录类型
			items = new List<SelectListItem>();

			var infos = StaffLoginContract.Entities.Where(p => p.StaffID.Equals(staffId) && !p.IsDeleted).Select(p => p.LoginType).ToList();
			foreach(string name in Enum.GetNames(typeof(Model.ViewModels.LoginType)))
			{
				Model.ViewModels.LoginType enumType = Model.ViewModels.LoginType.Account;
				if(Enum.TryParse<Model.ViewModels.LoginType>(name,true,out enumType))
				{
					if (infos.FindIndex(p => p == (int)enumType) < 0)
					{
						items.Add(new SelectListItem() { Text = enumType.ToDescription(), Value = ((int)enumType).ToString() });
					}
				}
			}
			ViewBag.selectLoginType = new SelectList(items, "Value", "Text");
				
			#endregion

			ViewData["staff"] = infoStaff;
			return View();
		}

		#endregion

		#region ActionResult LoginInsertAsync(StaffLogin entity)

		[Description("管理-登录配置添加")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult LoginInsertAsync(StaffLogin entity)
		{
			//所有AJAX的结果，返回统一数据格式
			var result = new AjaxResult();
			try
			{
				var query = StaffLoginContract.CheckExists(m => m.LoginType.Equals(entity.LoginType) && m.LoginName.Equals(entity.LoginName));
				if (query)
				{
					result.Type = AjaxResultType.Error;
					result.Content = "已经存在相同的信息";
				}
				else
				{
					//entity.LoginPass = Utility.Secutiry.HashHelper.GetMd5(entity.LoginPass);
					var count = StaffLoginContract.Insert(entity);
					if (count > 0)
					{
						result.Type = AjaxResultType.Success;
						result.Content = "录入成功";
					}
					else
					{
						result.Type = AjaxResultType.Error;
						result.Content = "录入失败";
					}
				}
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

		#endregion

		#region ActionResult LoginEdit(int id)

		[Description("管理-登录配置修改")]
		public ActionResult LoginEdit(int id)
		{
			var entity = StaffLoginContract.GetByKey(id);
			if (entity == null) throw new Exception("未找到该实体");

			var infoStaff = StaffContract.GetByKey(entity.StaffID);
			if (entity == null) throw new Exception("未找到该实体");

			#region SelectList

			List<SelectListItem> items = new List<SelectListItem>();

			//登录类型
			items = new List<SelectListItem>();

			var infos = StaffLoginContract.Entities.Where(p => p.StaffID.Equals(entity.StaffID) && !p.IsDeleted).Select(p => p.LoginType).ToList();
			foreach (string name in Enum.GetNames(typeof(Model.ViewModels.LoginType)))
			{
				Model.ViewModels.LoginType enumType = Model.ViewModels.LoginType.Account;
				if (Enum.TryParse<Model.ViewModels.LoginType>(name, true, out enumType))
				{
					if (entity.LoginType == (int)enumType || infos.FindIndex(p => p == (int)enumType) < 0)
					{
						items.Add(new SelectListItem() { Text = enumType.ToDescription(), Value = ((int)enumType).ToString() });
					}
				}
			}
			ViewBag.selectLoginType = new SelectList(items, "Value", "Text", entity.LoginType);

			#endregion
			
			ViewData["entity"] = entity;
			ViewData["staff"] = infoStaff;
			return View();
		}

		#endregion

		#region ActionResult LoginEditAsync(StaffLogin entity)

		[Description("管理-登录配置修改")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult LoginEditAsync(StaffLogin entity)
		{
			var result = new AjaxResult();
			try
			{
				var query = StaffLoginContract.CheckExists(m => m.LoginType.Equals(entity.LoginType) && m.LoginName.Equals(entity.LoginName) && m.Id != entity.Id);
				if (query)
				{
					result.Type = AjaxResultType.Error;
					result.Content = "已经存在相同的信息";
				}
				else
				{
					if (string.IsNullOrWhiteSpace(entity.LoginPass))
						//entity.LoginPass = Utility.Secutiry.HashHelper.GetMd5(entity.LoginPass);
					//else
						entity.LoginPass = StaffLoginContract.Entities.SingleOrDefault(p => p.Id == entity.Id).LoginPass;

					var count = StaffLoginContract.Update(entity);
					if (count > 0)
					{
						result.Type = AjaxResultType.Success;
						result.Content = "修改成功";
					}
					else
					{
						result.Type = AjaxResultType.Error;
						result.Content = "修改失败";
					}
				}
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

		#endregion

		#region ActionResult LoginDeleteAsync(string ids)

		[Description("管理-登录配置删除")]
		[HttpPost, AjaxOnly]
		public ActionResult LoginDeleteAsync(string ids)
		{
			var result = new AjaxResult();
			try
			{
				string[] idsStr = ids.Split(new char[] { ',' });
				int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
				StaffLoginContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new StaffLogin { IsDeleted = true });

				result.Type = AjaxResultType.Success;
				result.Content = "删除成功";
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

        #endregion
        #region 添加绑定
        public ActionResult GetRoleInsert()
        { 
            var list = RoleContract.TrackEntities.ToList();  
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }

        #endregion
        public ActionResult GetRole(int did)
        { 
            //var list = BuildingsContract.TrackEntities.Where(a => a.City.Equals(cid) && a.IsDeleted == false).ToList();//楼盘ID对应值  

            var list = from a in RoleContract.Entities
                       select new
                       {
                           ID = a.Id,
                           Name = a.Name,
                           Number = StaffRolesContract.Entities.Count(p => p.RoleID == a.Id && p.StaffID == did)
                       };

            return JsonEx(list.ToList(), JsonRequestBehavior.AllowGet);
        }
        #region 考勤规则
        public void interan()
        {
            List<SelectListItem> GridData = new List<SelectListItem>();
            var data = from s in SideModuleContract.Entities.ToList()
                       select new SelectListItem
                       {
                           Value = s.Id + "",
                           Text =s.StartTime.ToString("HH:mm") + "-" +s.EndTime.ToString("HH:mm")
                       }; 
            GridData.AddRange(data);
            ViewBag.sentity = new SelectList(GridData);
        }
        #endregion
        #region 角色
        public ActionResult IndexRole(int id)
        {
            var entityRole = StaffRolesContract.TrackEntities.Where(m => m.StaffID == id).ToList();
            ViewBag.entityRole = entityRole;
            ViewBag.id = id;
            InnerRole();
            return View();
        }
        #endregion 
        #region 角色添加
        public ActionResult EditRoleAsync()
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            result.Type = AjaxResultType.Success;
            result.Content = "修改成功";

            try
            {
                var staffrole = Request["RoleId"];
                var staffid = Convert.ToInt32(Request["Id"]);
                //查询工作人员ID的角色ID
                var roleid = StaffRolesContract.TrackEntities.Where(p => p.StaffID == staffid).ToList();

                //事务开始
                StaffRolesContract.Repository.UnitOfWork.BeginTransaction();

                //删除角色原有记录
                for (int i = 0; i < roleid.Count; i++)
                {
                    StaffRolesContract.Delete(roleid[i].Id);
                }

                if (staffrole != null)
                {
                    //添加选中现有记录
                    var RoleID = staffrole.Split(',');
                    StaffRoles Roles = new StaffRoles();
                    for (int i = 0; i < RoleID.Length; i++)
                    {
                        Roles.StaffID = staffid;
                        Roles.RoleID = Convert.ToInt32(RoleID[i]);
                        int count = StaffRolesContract.Insert(Roles);
                        if (count < 1)
                        {
                            result.Type = AjaxResultType.Error;
                            result.Content = "修改失败";
                            break;
                        }
                    }                                        
                } 

                //事务结束
                StaffRolesContract.Repository.UnitOfWork.Commit();                
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion
        #region 角色列表
        public void InnerRole()
        { 
            List<SelectListItem> GridData = new List<SelectListItem>();
            var RoleList = from r in RoleContract.Entities 
                                select new SelectListItem
                                {
                                    Value = r.Id + "",
                                    Text = r.Name
                                };
            GridData.AddRange(RoleList);
            ViewBag.RoleList = new SelectList(GridData);
        }
        #endregion
        #region 权限
        public ActionResult Jurisdiction(int id)
        {
            var One = AuthorityGroupContract.Entities.Where(m => m.Id == 1).FirstOrDefault();
            var Tow = AuthorityGroupContract.Entities.Where(m => m.Id == 2).FirstOrDefault();
            var Three = AuthorityGroupContract.Entities.Where(m => m.Id == 3).FirstOrDefault();
            var Four = AuthorityGroupContract.Entities.Where(m => m.Id == 4).FirstOrDefault();
            var Five = AuthorityGroupContract.Entities.Where(m => m.Id == 5).FirstOrDefault();
            var Six = AuthorityGroupContract.Entities.Where(m => m.Id == 6).FirstOrDefault();
            ViewBag.One = One.Name;
            ViewBag.Tow = Tow.Name;
            ViewBag.Three = Three.Name;
            ViewBag.Four = Four.Name;
            ViewBag.Five = Five.Name;
            ViewBag.Six = Six.Name;
            var entity = StaffAuthorityContract.Entities.Where(m => m.StaffID == id).ToList();
            ViewBag.entity = entity;
            ViewBag.StaffID = id;
            Inner();
            return View();
        }
        #endregion
        #region 权限添加
        public ActionResult JurisdictionAsync(StaffAuthority entity)
        {
            var result = new AjaxResult();
            var AuthorityID = Request["authorityid"];
            if (AuthorityID == null)
            {
                try
                {
                    //事务开始
                    StaffAuthorityContract.Repository.UnitOfWork.BeginTransaction();
                    //删除原有权限 
                    var DeleteEntity = StaffAuthorityContract.Entities.Where(m => m.StaffID == entity.StaffID).ToList();
                  
                    for (int o = 0; o < DeleteEntity.Count(); o++)
                    {
                        StaffAuthorityContract.DeleteDirect(DeleteEntity[o].Id);
                    }

                    StaffAuthorityContract.Repository.UnitOfWork.Commit();

                }
                catch (Exception)
                {
                    StaffAuthorityContract.Repository.UnitOfWork.Rollback();
                    throw;
                }
                result.Type = AjaxResultType.Success;
                result.Content = "添加成功";
            }
            else
            {
                var authorityid = AuthorityID.Split(',');
                var count = 0;
                try
                {
                    StaffAuthorityContract.Repository.UnitOfWork.BeginTransaction();
                    //删除原有权限 
                    var DeleteEntity = StaffAuthorityContract.Entities.Where(m => m.StaffID == entity.StaffID).ToList();
                    //var a = DeleteEntity
                    for (int o = 0; o < DeleteEntity.Count(); o++)
                    {
                        StaffAuthorityContract.DeleteDirect(DeleteEntity[o].Id);
                    }
                    for (int i = 0; i < authorityid.Length; i++)
                    {
                        entity.AuthorityID = Convert.ToInt32(authorityid[i]);
                        count = StaffAuthorityContract.Insert(entity);
                    }
                    StaffAuthorityContract.Repository.UnitOfWork.Commit();
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "添加成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "添加失败";
                    }
                }
                catch
                {
                    //事务结束
                    StaffAuthorityContract.Repository.UnitOfWork.Rollback();

                    result.Type = AjaxResultType.Error;
                    result.Content = "异常操作";
                }
            }
            return JsonEx(result);
        }
        #endregion
        #region 菜单与权限
        public void Inner()
        {
            //编号1基础菜单0
            List<SelectListItem> GridData = new List<SelectListItem>();
            var OneEntityZero = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 1 && a.IsMenu == 0
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(OneEntityZero);
            ViewBag.OneEntityZero = new SelectList(GridData);
            //编号1基础权限1
            GridData = new List<SelectListItem>();
            var OneEntityOne = from ag in AuthorityGroupContract.Entities
                               join a in AuthorityContract.Entities
                               on ag.Id equals a.AuthorityGroupID
                               where ag.Id == 1 && a.IsMenu == 1
                               select new SelectListItem
                               {
                                   Value = a.Id + "",
                                   Text = a.Name
                               };
            GridData.AddRange(OneEntityOne);
            ViewBag.OneEntityOne = new SelectList(GridData);
            //编号2新房菜单0
            GridData = new List<SelectListItem>();
            var TowEntityZero = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 2 && a.IsMenu == 0
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(TowEntityZero);
            ViewBag.TowEntityZero = new SelectList(GridData);
            //编号2新房权限1
            GridData = new List<SelectListItem>();
            var TowEntityOne = from ag in AuthorityGroupContract.Entities
                               join a in AuthorityContract.Entities
                               on ag.Id equals a.AuthorityGroupID
                               where ag.Id == 2 && a.IsMenu == 1
                               select new SelectListItem
                               {
                                   Value = a.Id + "",
                                   Text = a.Name
                               };
            GridData.AddRange(TowEntityOne);
            ViewBag.TowEntityOne = new SelectList(GridData);
            //编号3低价房菜单0
            GridData = new List<SelectListItem>();
            var ThreeEntityZero = from ag in AuthorityGroupContract.Entities
                                  join a in AuthorityContract.Entities
                                  on ag.Id equals a.AuthorityGroupID
                                  where ag.Id == 3 && a.IsMenu == 0
                                  select new SelectListItem
                                  {
                                      Value = a.Id + "",
                                      Text = a.Name
                                  };
            GridData.AddRange(ThreeEntityZero);
            ViewBag.ThreeEntityZero = new SelectList(GridData);
            //编号3低价房权限1
            GridData = new List<SelectListItem>();
            var ThreeEntityOne = from ag in AuthorityGroupContract.Entities
                                 join a in AuthorityContract.Entities
                                 on ag.Id equals a.AuthorityGroupID
                                 where ag.Id == 3 && a.IsMenu == 1
                                 select new SelectListItem
                                 {
                                     Value = a.Id + "",
                                     Text = a.Name
                                 };
            GridData.AddRange(ThreeEntityOne);
            ViewBag.ThreeEntityOne = new SelectList(GridData);
            //编号4二手房菜单0
            GridData = new List<SelectListItem>();
            var FourEntityZero = from ag in AuthorityGroupContract.Entities
                                 join a in AuthorityContract.Entities
                                 on ag.Id equals a.AuthorityGroupID
                                 where ag.Id == 4 && a.IsMenu == 0
                                 select new SelectListItem
                                 {
                                     Value = a.Id + "",
                                     Text = a.Name
                                 };
            GridData.AddRange(FourEntityZero);
            ViewBag.FourEntityZero = new SelectList(GridData);
            //编号4二手房权限1
            GridData = new List<SelectListItem>();
            var FourEntityOne = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 4 && a.IsMenu == 1
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(FourEntityOne);
            ViewBag.FourEntityOne = new SelectList(GridData);
            //编号5装修菜单0
            GridData = new List<SelectListItem>();
            var FiveEntityZero = from ag in AuthorityGroupContract.Entities
                                 join a in AuthorityContract.Entities
                                 on ag.Id equals a.AuthorityGroupID
                                 where ag.Id == 5 && a.IsMenu == 0
                                 select new SelectListItem
                                 {
                                     Value = a.Id + "",
                                     Text = a.Name
                                 };
            GridData.AddRange(FiveEntityZero);
            ViewBag.FiveEntityZero = new SelectList(GridData);
            //编号5装修权限1
            GridData = new List<SelectListItem>();
            var FiveEntityOne = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 5 && a.IsMenu == 1
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(FiveEntityOne);
            ViewBag.FiveEntityOne = new SelectList(GridData);
            //编号6金融菜单0
            GridData = new List<SelectListItem>();
            var SixEntityZero = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 6 && a.IsMenu == 0
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(SixEntityZero);
            ViewBag.SixEntityZero = new SelectList(GridData);
            //编号6金融权限1
            GridData = new List<SelectListItem>();
            var SixEntityOne = from ag in AuthorityGroupContract.Entities
                               join a in AuthorityContract.Entities
                               on ag.Id equals a.AuthorityGroupID
                               where ag.Id == 6 && a.IsMenu == 1
                               select new SelectListItem
                               {
                                   Value = a.Id + "",
                                   Text = a.Name
                               };
            GridData.AddRange(SixEntityOne);
            ViewBag.SixEntityOne = new SelectList(GridData);
        }
        #endregion
    }
}